<template>
  <div class="popup">
    <div class="tab-bar">
      <div
        :class="['item', active === 'otp' ? 'active' : '']"
        @click="active = 'otp'"
      >
        授权码
      </div>
      <div
        :class="['item', active === 'pass' ? 'active' : '']"
        @click="active = 'pass'"
      >
        账号密码
      </div>
    </div>
    <div class="content">
      <div class="list" v-show="active === 'otp'">
        <div class="item" v-for="item in otpList" @click="handleClick(item)">
          <div class="countdown">{{ item.issuer }}</div>
          <div class="title" :style="{ color: getColorByProgress }">
            {{ item.secret }}
          </div>
        </div>
      </div>
      <div class="list" v-show="active === 'pass'">
        <div
          class="item"
          v-for="item in passList"
          @click="handlePassClick(item)"
        >
          <div class="countdown">{{ item.account }}</div>
          <div class="title">
            {{ item.remark }}
          </div>
        </div>
      </div>
    </div>
    <div class="add-pass" @click="handleAdd">设置</div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { getStorage, setStorage, getStorageSync } from '../utils/storage';
import * as OTPAuth from 'otpauth';
import { ConfigStorage, GiteeConfigStorage } from '../components/config/index';

const active = ref('otp');

interface PassItem {
  account: string;
  pass: string;
  selectorAccount: string;
  selectorPass: string;
  remark: string;
  submit: string;
}
interface Item {
  issuer: string;
  secret: string;
  submit: string;
  selector: string;
}
const otpList = ref<Item[]>([]);

const passList = ref<PassItem[]>([]);

// 添加进度状态
const progress = ref(30); // 初始值设为30秒

// 计算属性：根据进度返回颜色
const getColorByProgress = computed(() => {
  // 将颜色从黑色 #000000 渐变到橙色 #e86806
  const startColor = { r: 0, g: 0, b: 0 };
  const endColor = { r: 232, g: 104, b: 6 };

  // 计算当前进度的颜色值
  const currentColor = {
    r: Math.round(
      startColor.r + (endColor.r - startColor.r) * (1 - progress.value / 30),
    ),
    g: Math.round(
      startColor.g + (endColor.g - startColor.g) * (1 - progress.value / 30),
    ),
    b: Math.round(
      startColor.b + (endColor.b - startColor.b) * (1 - progress.value / 30),
    ),
  };

  return `rgb(${currentColor.r}, ${currentColor.g}, ${currentColor.b})`;
});

const handleClick = (item: Item) => {
  // @ts-ignore
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    // @ts-ignore
    chrome.tabs.sendMessage(tabs[0].id!, {
      type: 'FILL_INPUT',
      value: [
        {
          selector: item.selector,
          value: item.secret,
        },
      ],
      submit: item.submit,
    });
    // 关闭popup
    window.close();
  });
};

const handlePassClick = (item: PassItem) => {
  // @ts-ignore
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    // @ts-ignore
    chrome.tabs.sendMessage(tabs[0].id!, {
      type: 'FILL_INPUT',
      value: [
        {
          selector: item.selectorAccount,
          value: item.account,
        },
        {
          selector: item.selectorPass,
          value: item.pass,
        },
      ],
      submit: item.submit,
    });
    // 关闭popup
    window.close();
  });
};

const handleGet = () => {
  getStorageSync('remote').then((result) => {
    console.log('result', result);
    if (result && result.open === 'ok') {
      const storage: ConfigStorage = new GiteeConfigStorage({
        owner: 'lsl52640',
        repo: 'code111',
        filePath: 'config.json',
      });
      storage.load().then((result) => {
        console.log('result', result);
      });
    } else {
      getStorage('otpList', (result) => {
        if (result) {
          otpList.value = [];
          for (const item of result) {
            let token = OTPAuth.TOTP.generate({
              secret: OTPAuth.Secret.fromBase32(item.otp),
              period: 30,
            }); // 30s
            otpList.value.push({
              secret: token,
              issuer: item.issuer,
              submit: item.submit,
              selector: item.selector,
            });
          }
        }
      });
    }
  });
};
const getPassList = () => {
  getStorage('passList', (result) => {
    console.log('getPassList', result);
    if (result) {
      passList.value = result;
    }
  });
};
const handleAdd = () => {
  // @ts-ignore
  chrome.runtime.openOptionsPage();
};
// 更新定时器逻辑
onMounted(() => {
  handleGet();
  getPassList();
  // 每秒更新进度
  setInterval(() => {
    progress.value = Math.floor((30000 - (new Date().getTime() % 30000)) / 300);
    // 当进度接近0时更新OTP
    if (progress.value < 1) {
      setTimeout(() => {
        handleGet();
      }, 500);
    }
  }, 300);
});
</script>

<style scoped lang="scss">
@use '../vars.scss';
.popup {
  width: 260px;
  max-height: 500px;
  display: flex;
  flex-direction: column;
  .tab-bar {
    display: flex;
    padding: 8px 16px;
    font-size: 16px;
    gap: 8px;
    background-color: #fff;

    .item {
      cursor: pointer;
      padding: 3px 12px;
      border-bottom: 2px solid transparent;
      &:hover {
        color: vars.$primary-color;
        font-weight: 700;
      }
      &.active {
        border-color: vars.$primary-color;
        font-weight: 700;
      }
    }
  }
  .progress-bar {
    height: 6px;
    background: vars.$primary-color;
  }
  .content {
    flex: 1;
    padding: 10px 0px;
    display: flex;
    background: #fff;
    border-bottom: 1px solid #eee;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: center;
    .list {
      display: flex;
      flex: 1;
      gap: 15px;
      flex-direction: column;
      font-size: 15px;
      .active {
        color: vars.$primary-color;
        border-bottom: 1px solid vars.$primary-color;
      }
      .item {
        display: flex;
        background: #fff;
        padding: 12px 10px;
        gap: 10px;
        align-items: center;
        cursor: pointer;
        .countdown {
          font-size: 14px;
          color: #6d6767;
          width: 25%;
        }
        .title {
          font-size: 20px;
          color: #000;
          font-weight: bold;
        }
        &:hover {
          background: #f5f5f5;
        }
      }
    }
    .tool {
      padding: 0px 10px;
    }
  }
  .add-pass {
    display: flex;
    padding: 10px 5px;
    cursor: pointer;
    &:hover {
      color: vars.$hover-color;
    }
  }
  .tab-con {
    display: flex;
    gap: 15px;
    padding: 6px 10px;
    flex-wrap: wrap;
    justify-content: space-between;
    .active {
      display: block;
    }
    .hide {
      display: none;
    }
    .it {
      min-width: 60px;
      padding: 6px 10px;
      background: #fff;
      cursor: pointer;
      border-radius: 5px;
      font-size: 15px;
      &:hover {
        color: vars.$hover-color;
      }
    }
  }
}
</style>
